package com.etop.weiway.wxmanage.controller;

import com.etop.weiway.basic.controller.BaseController;
import com.etop.weiway.commons.web.Pager;
import com.etop.weiway.wxmanage.entity.Account;
import com.etop.weiway.wxmanage.entity.User;
import com.etop.weiway.wxmanage.service.AccountService;
import com.etop.weiway.wxmanage.service.WxUserManageService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 公众号管理控制器
 * Created by Jeremie on 2014/12/11.
 */
@Controller
@RequestMapping("/wxmanager/account")
public class AccountController extends BaseController {

    @Autowired
    private AccountService accountService;
    @Autowired
    private WxUserManageService wxUserManageService;

    /**
     * 注入公众号信息
     *
     * @param tempId
     * @return
     * @throws Exception
     */
    @ModelAttribute(value = "account")
    public Account get(@RequestParam(required = false,value = "id") String tempId)
            throws Exception {
        try {
            Integer id = Integer.parseInt(tempId);
            if (id != null && id > 0) {
                return accountService.loadAccount(id);
            } else {
                return new Account();
            }
        }catch (NumberFormatException e){
            return new Account();
        }
    }

    /**
     * 跳转到公众号信息添加修改页面
     *
     * @param account
     * @param model
     * @return
     */
    @RequiresPermissions("menu:account")
    @RequestMapping(value = "/edit", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
    public String form(@ModelAttribute(value = "account") Account account,
                       Model model) throws Exception {
        model.addAttribute("account", account);
        return "/home/wxmanage/base/accountManage/edit";
    }

    /**
     * 保存或更新公众号信息
     *
     * @param account
     * @param model
     * @param oldWechatId
     * @param redirectAttributes
     * @return
     * @throws Exception
     */
    @RequiresPermissions("menu:account")
    @RequestMapping(value = "/edit", method = RequestMethod.POST, produces = "text/html; charset=utf-8")
    public String save(Account account, Model model, String oldWechatId, String syncFlag,
                       RedirectAttributes redirectAttributes, HttpSession httpSession) throws Exception {
        //检测名称是否存在
        if (!oldWechatId.equals(account.getWechatId())
                && accountService.loadAccountByWechatId(account.getWechatId()) != null) {
            addMessage(model, ERROR, "保存公众号<" + account.getWechatId()
                    + ">失败，公众号已存在！");
            account.setWechatId(oldWechatId);
            return form(account, model);
        }
        if (httpSession.getAttribute("currentAccoutId") == null) {
            accountService.saveAccount(account, true);
            httpSession.setAttribute("currentAccoutId", account.getId());
            httpSession.setAttribute("account", account);
        } else {
            accountService.saveAccount(account, false);
            httpSession.setAttribute("account", account);
        }

        //用户选择同步数据时，才执行下面这个方法
        if ("1".equals(syncFlag)) {
            wxUserManageService.saveWxUserList(accountService.loadAccount((Integer) httpSession.getAttribute("currentAccoutId")));
        }

        addMessage(redirectAttributes, SUCCESS, "保存公众号<" + account.getName() + ">成功！");
        return "redirect:/wxmanager/account/list";
    }

    /**
     * 分页列出公众号信息
     *
     * @param account
     * @param request
     * @param response
     * @param model
     * @return
     * @throws Exception
     */
    @RequiresPermissions("menu:account")
    @RequestMapping(value = "/list", produces = "text/html; charset=utf-8")
    public String listAccount(@ModelAttribute(value = "account") Account account, String info,
                              HttpServletRequest request, HttpServletResponse response, Model model, HttpSession session) throws Exception {
        Pager<Account> accountPager =
                accountService.getAccountByPage(new Pager<>(request, response), account.getName(), ((User) session.getAttribute("user")).getId());
        model.addAttribute(accountPager);
        model.addAttribute("search", account.getName());
        if (info != null && !"".equals(info)) {
            request.setAttribute("message", "还未设置当前公众号！");
            request.setAttribute("type", ERROR);
        }
        return "/home/wxmanage/base/accountManage/list";
    }

    /**
     * 选择当前公众号
     *
     * @param id
     * @param session
     * @return
     */
    @RequiresPermissions("menu:account")
    @RequestMapping(value = "/select", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
    public String selectCurrentAccount(Integer id, HttpSession session) throws Exception {
        accountService.saveCurrentAccount(id, ((User) session.getAttribute("user")).getId());
        session.setAttribute("currentAccoutId", id);
        session.setAttribute("account", accountService.loadAccount(id));
        return "redirect:/wxmanager/account/list";
    }

    /**
     * 删除公众号
     *
     * @param id
     * @param redirectAttributes
     * @return
     * @throws Exception
     */
    @RequiresPermissions("menu:account")
    @RequestMapping(value = "/delete", produces = "text/html; charset=utf-8")
    public String deleteAccount(int id, RedirectAttributes redirectAttributes, HttpSession session) throws Exception {
        Integer currentId = (Integer) session.getAttribute("currentAccoutId");
        if (currentId == id) {
            session.removeAttribute("currentAccoutId");
            Account account = accountService.deleteAccountById(id, true);
            User user = (User) session.getAttribute("user");
            if (account != null) {
                session.setAttribute("currentAccoutId", account.getId());
                session.setAttribute("account", account);
                user.setCurrentAccount(account);
            } else {
                user.setCurrentAccount(null);
                session.removeAttribute("currentAccoutId");
                session.removeAttribute("account");
            }
            session.setAttribute("user", user);
        } else accountService.deleteAccountById(id, false);
        addMessage(redirectAttributes, SUCCESS, "删除公众号成功！");
        return "redirect:/wxmanager/account/list";
    }

    /**
     * 上传头像
     *
     * @param file
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/upload", produces = "text/html; charset=utf-8")
    public String uploadPortrait(MultipartFile file, HttpServletRequest request, HttpSession session) throws Exception {
        if (session.getAttribute("user")!=null) {
            //组成路径
            String path = request.getServletContext().getRealPath("/");
            if (!path.endsWith("/"))
                path += "/";
            path += "home/wxmanage/upload/" + ((User) session.getAttribute("user")).getId() + "/image";
            return accountService.savePortrait(path, file);
        }
        return "error:用户未登陆";
    }

    /**
     * 删除头像
     *
     * @param fileName
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/deleteImg", produces = "text/html; charset=utf-8")
    public String deleteImg(String fileName, HttpServletRequest request, HttpSession session) throws Exception {
        if (session.getAttribute("user")!=null) {
            //组成路径
            String path = request.getServletContext().getRealPath("/");
            if (!path.endsWith("/"))
                path += "/";
            path += "home/wxmanage/upload/" + ((User) session.getAttribute("user")).getId() + "/image";
            if (accountService.deleteImg(path, fileName)) {
                return "true";
            } else {
                return "error:删除失败";
            }
        }
        return "error:用户未登陆";
    }

    /**
     * 同步微信用户
     *
     * @param accountId
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/sync")
    public String syncWxUser(String accountId) throws Exception {
        wxUserManageService.saveWxUserList(accountService.loadAccount(Integer.parseInt(accountId)));
        return "info:success";
    }

    /**
     * 异步校验appId和appSecret是否填写正确
     *
     * @param appId
     * @param appSecret
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/chkApp")
    public String checkApp(String appId, String appSecret) throws Exception {
        if (accountService.checkGetAccessToken(appId, appSecret)) {
            return "info:success";
        } else {
            return "info:fail";
        }
    }
}
